package org.example.config;

import org.example.bean.Constants;
import org.example.bean.UserBean;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //不需要登录就可以访问的路径
        String requestUrl = request.getRequestURI();
        if (requestUrl.contains(".") || requestUrl.startsWith("/"+ Constants.RESOURCE_COMMON + "/")){
            return true;
        }

        //未登录用户直接拒绝访问
        if (null == request.getSession().getAttribute(Constants.FLAG_CURRENT_USER)){
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write("please login first");
            return false;
        }else {

            UserBean user = (UserBean) request.getSession().getAttribute(Constants.FLAG_CURRENT_USER);
            //已登录用户，判断是否有资源访问权限
            if (requestUrl.startsWith("/" + Constants.RESOURCE_MOBILE + "/")
                    && user.havePermission(Constants.RESOURCE_MOBILE)){
                return true;
            }else if (requestUrl.startsWith("/" + Constants.RESOURCE_SALARY + "/")
                    && user.havePermission(Constants.RESOURCE_SALARY)){
                return true;
            }else {
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write("no auth to visit");
                return false;
            }

        }
    }
}
